unit uContentBlocker;

{$mode objfpc}{$H+}

interface

uses
    Classes, SysUtils, contnrs, Dialogs,
    RegExpr;

function IsURLBlack(const AURL: string; var ATemplate: string): Boolean;
procedure InitContentBlocker;
procedure ReloadContentBlocker;

implementation

var
    FBlackList: TStringList;
    FBlackListRegExp: TFPObjectList;

function IsURLBlack(const AURL: string; var ATemplate: string): Boolean;
var
    s, t: string;
    i: Integer;
    c: Integer;
begin
    Result := False;
    ATemplate := '';
    s := LowerCase(AURL);

    // Templates
    // -----------------------------------------------------
    for i := 0 to FBlackList.Count - 1 do
    begin
        t := LowerCase(FBlackList[i]);

        Result := Pos(t, s) > 0;
        if Result then
        begin
            ATemplate := t;
            Break;
        end;
    end;

    // RegEx
    // -----------------------------------------------------
    if not Result then
    begin
        c := FBlackListRegExp.Count;
        for i := 0 to c - 1 do
        begin
            Result := TRegExpr(FBlackListRegExp[i]).Exec(s);
            if Result then
            begin
                ATemplate := TRegExpr(FBlackListRegExp[i]).Expression;
                Break;
            end;
        end;
    end;
end;

procedure InitContentBlocker;
begin
    FBlackList := TStringList.Create;
    FBlackListRegExp := TFPObjectList.Create(True);
    FBlackListRegExp.OwnsObjects := True;

    ReloadContentBlocker;
end;

procedure ReloadContentBlocker;
var
    fn: string;
    r: TStringList;
    re: TRegExpr;
    i: Integer;
begin
    fn := './data/blacklst.dat';
    if FileExists(fn) then
        FBlackList.LoadFromFile(fn);

    FBlackListRegExp.Clear;
    fn := './data/blacklst.rge';
    if FileExists(fn) then
    begin
        r := TStringList.Create;
        try
            r.LoadFromFile(fn);

            for i := 0 to r.Count - 1 do
            begin
                re := TRegExpr.Create;
                re.Expression := r[i];
                re.Compile;
                FBlackListRegExp.Add(re);
            end;
        finally
            r.Free;
        end;
    end;
end;

initialization
    InitContentBlocker;

end.

